#include <glog/logging.h>

#include "file_system/file_writer/normal_file_writer.h"

namespace hawking {
namespace indexlib {

Status NormalFileWriter::Init() {
    fd_ = open(filename_.data(), O_CREAT | O_RDWR | O_TRUNC);
    if (fd_ == -1) {
        PLOG(ERROR) << "open filename " << filename_ << " fail.";
        return Status::IOError;
    }

    struct stat statbuf;
    fstat(fd_, &statbuf);
    file_size_ = statbuf.st_size;
    return Status::OK;
}

void NormalFileWriter::ReserveFile(size_t length) {
    if (length <= file_size_) {
        return;
    }

    size_t inc = length - file_size_;
    fallocate(fd_, 0, file_size_, inc);
}

ReturnValue<size_t> NormalFileWriter::Write(uint8_t* buf, size_t len, off_t offset) {
    size_t ret = 0;
    if (len > 0) {
        ret = ::pwrite(fd_, buf, len, offset);
    }
    
    if (ret == -1) {
        return ReturnValue<size_t>(Status::IOError, 0);
    }

    return ReturnValue<size_t>(Status::OK, ret);
}

}
}
